#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import subprocess


def sort(source_file, target_file, col, r):
    sort = subprocess.Popen("sort -t '\t' -k%d -n%s " % (col, r), shell=True,
                    stdin=open(source_file, 'r'),
                    stdout=open(target_file, 'w'),
           )
    
def cal_index_minus(old_file, new_file, output_file):
    node_dict = {}
    
    i = 1
    with open(old_file, 'r+') as f:
        for line in f:
            arr = line.strip().split('\t')
            node_dict[arr[0]] = [i]
            i += 1
    f.close()
    i = 1
    with open(new_file, 'r+') as f:
        for line in f:
            arr = line.strip().split('\t')
            node_dict[arr[0]].append(i) 
            i += 1 
    f.close
    
    opf = open(output_file, 'w+')
    for k, v in node_dict.iteritems():
        opf.write('%s\t%d\t%d\t%d\n' % (k, v[0], v[1], v[0]-v[1]))  
    opf.flush()
    opf.close()      

def graph(index_file):
    arr = []
    with open(index_file, 'r+') as f:
        for line in f:
            arr.append(int(line.strip().split('\t')[3]))
    f.close()
    print 'max: %d, min: %d' % (int(max(arr)),int(min(arr)))
    
    fig = plt.figure()
    n, bins, patches = plt.hist(arr)
#     plt.axis([0, 10000, 0, 350000])
    plt.title('Changes of PageRank Distribution')
    plt.xlabel('PageRank Changes')
    plt.ylabel('Count')
    plt.show()
    fig.savefig('/home/ivy/git/BD_py/PageRank_py/project/resource/sort_all/distribution_test.png', \
            bbox_inches='tight')

def main():
    pagerank_old = '/home/ivy/git/BD_py/PageRank_py/project/resource/pagerank_old.txt'
    sort_old = '/home/ivy/git/BD_py/PageRank_py/project/resource/sort_all/sort_old.txt'
    pagerank_new = '/home/ivy/git/BD_py/PageRank_py/project/resource/pagerank.txt'
    sort_new = '/home/ivy/git/BD_py/PageRank_py/project/resource/sort_all/sort_new.txt'
    index_file = '/home/ivy/git/BD_py/PageRank_py/project/resource/sort_all/index_old_new_minus.txt'
    temp_file = '/home/ivy/git/BD_py/PageRank_py/project/resource/sort_all/temp.txt'
#     sort(pagerank_old, sort_old, 2)
#     sort(pagerank_new, sort_new, 2)
#     cal_index_minus(sort_old, sort_new, temp_file)
#     sort(index_file, temp_file, 4, '')
    graph(index_file)

if __name__ == '__main__':
    main()


